import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'
import Layout from "@/layouts/index.vue"


// 重置路由
export const resetRouter = (): void => {
  // 白名单路由列表 若name可匹配到下列列表，则无需重置
  const resetWhiteNameList: string[] = ['LoginView', 'RootView']
  router.getRoutes().forEach(route => {
    const { name } = route
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

// 加载静态路由
export const loadStaticRoutes = (): void => {
  // 先根据Name找出本地还未加载的路由
  let staticRouterss = staticRouters.filter((item: any) => !router.hasRoute(item.name))
  staticRouterss.forEach((item: any) => {
    router.addRoute(item)
  })
}


export const staticRouters = [
  {
    path: '/',
    redirect: '/login',
    hidden: true
  },
  {
    path: "/login",
    name: "LoginView",
    meta: {
      title: "登录"
    },
    component: () => import('@/views/login/LoginView.vue'),
    hidden: true,
  },
  {
    path: "/dashboard",
    name: "Dashboard",
    meta: {
      title: ""
    },
    component: () => Layout,
    children:[
      {
        path: "/dashboard/analysis",
        name: "Analysis",
        meta: {
          title: "首页"
        },
        component: () => import('@/views/menus/dashboard/index.vue'),
      }
    ]
  },
  {
    path: "/403",
    name: "N403",
    meta: {
      title: "403"
    },
    component: () => import('@/views/errors/403.vue'),
    hidden: true,
  },
  {
    path: "/404",
    name: "N404",
    meta: {
      title: "404"
    },
    component: () => import('@/views/errors/404.vue'),
    hidden: true,
  },
  // 其他的没有匹配就跳转至404 
  {
    path: '/:pathMatch(.*)*',
    redirect: "/404",
    hidden: true,
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  strict: true,
  routes: staticRouters as RouteRecordRaw[],
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { left: 0, top: 0 }
    }
  }
})

export const setupRouter = (app: App<Element>) => {
  app.use(router)
}

export default router